
import React, {PureComponent, PropTypes} from 'react';

import styles from './style.scss';

export  default  class ProgressBar extends PureComponent {

    state = {
        moveX:0,
        maxMoveX:0
    };

    canDrag = false;

    percentage = 0;

    static propTypes = {
        percentage:PropTypes.number,
        onChange:PropTypes.func
    };

    static defaultProps ={
        percentage:0,
        onChange:()=>{}
    };

    componentWillReceiveProps(nextProps){
        const { percentage } = nextProps;
        if(this.percentage !== percentage) {
            this.percentage = percentage;
            this.update();
        }
    }

    update(){
        const { width } = this.dragel.getBoundingClientRect();
        this.setState({
            moveX:~~width * this.percentage,
            maxMoveX:~~width
        });
    }

    onTouchMove(e){
        this.touchEvent(e);
    }

    onTouchEnd() {
        this.canDrag = false;
    }

    onTouchStart (e) {
        this.canDrag=true;
        this.touchEvent(e);
    }

    touchEvent({ touches , currentTarget }){
        const { onChange } = this.props;
        const event = touches[0];
        const pageX = event.pageX;
        const { x , width } = currentTarget.getBoundingClientRect();
        let moveX = pageX-x;
        if(moveX <= 0) moveX = 0;
        if(moveX >= width) moveX=width;
        this.setState({
            moveX:~~moveX,
            maxMoveX:~~width
        },()=>{
            onChange(~~moveX/~~width)
        });
    }

    getPosX(moveX) {
        const { maxMoveX } = this.state;
        if( maxMoveX > 0) {
            moveX = moveX - 16;
            if(moveX <= 0 ) moveX = 0;
            return moveX;
        } else {
            return 0;
        }
    }

    render(){
        const { moveX , maxMoveX } = this.state;
        return (
            <div
                className={styles.progress_bar_wrap}
                onTouchEnd={e=>this.onTouchEnd(e)}
                onTouchMove={e=>this.canDrag && this.onTouchMove(e)}
                onTouchStart={e=>this.onTouchStart(e)}
                ref={e=>this.dragel=e}
            >
                <div className={styles.progress_bar_inner}>
                    <div
                        className={styles.progress_bar_bg}
                        style={{
                            width:moveX
                        }}
                    />
                </div>
                <div
                    className={styles.progress_bar_btn}
                    style={{
                        transform:`translateX(${this.getPosX(moveX)}px)`
                    }}
                />
            </div>
        )
    }
}